<template>
<!--  使用v-if 可以解决 因异步加载导致页面无法找到property的问题-->
  <div v-if="carList[0]">
<!--    轮播图-->
    <van-swipe :autoplay="3000">
      <van-swipe-item v-for="(image, index) in images" :key="index"height="200px">
        <img width="100%" height="240px" v-lazy="image" />
      </van-swipe-item>
    </van-swipe>


    <div>
      <div>
        &nbsp;&nbsp;&nbsp;&nbsp;{{carList[0]['name']}}
      </div>
      <div style="height: 6px"></div>
      <div>
        <van-row>
          <van-col span="1"></van-col>
          <van-col span="4">
            <div style="border-radius:3px;border: 1px solid #c8c9cc ">
              <span  style="color: #ee0a24;font-size: 13px">&nbsp;颜色</span>
              <span  style="color: #c8c9cc;font-size: 13px">|{{carList[0]['color']}}</span>
            </div>
          </van-col>
          <van-col span="1"></van-col>
          <van-col span="4">
            <div style="border-radius:3px;border: 1px solid #c8c9cc ">
              <span  style="color: #ee0a24;font-size: 13px">&nbsp;款式</span>
              <span  style="color: #c8c9cc;font-size: 13px">|{{carList[0]['type']}}</span>
            </div>
          </van-col>
          <van-col span="1"></van-col>
          <van-col span="7">
            <div style="border-radius:3px;border: 1px solid #c8c9cc ">
              <span  style="color: #ee0a24;font-size: 13px">&nbsp;车牌</span>
              <span  style="color: #c8c9cc;font-size: 13px">|{{carList[0]['carnumber']}}</span>
            </div>
          </van-col>
        </van-row>

        <span >

        </span>

      </div>

    </div>
<!--    栅格-->

    <van-field
      v-model="message"
      rows="2"
      autosize
      type="textarea"
      maxlength="50"
      placeholder="快来评论吧~~"
      show-word-limit
    >
      <template #button>
        <van-button size="small" type="primary" v-on:click="commitComment" :disabled="message == ''">发表</van-button>
      </template>
    </van-field>


    <div v-if="records.length > 0">
      <!--    评论板块-->
      <div style="height: 15px"></div>
      <van-row v-for="(item,i) in records">
        <van-col span="4" class="headPortrait">
  <!--        这里是头像-->
          <van-image
          round
          width="2.5rem"
          height="2.5rem"
          fit="cover"
          :src="item.customer.headPortrait"
          /><!--https://img01.yzcdn.cn/vant/cat.jpeg-->
        </van-col>
        <van-col span="20"  style="height: 70px">
        <!--  昵称和评论内容-->
          <div class="nickname"><span class="nickname">{{item.customer.name}}</span><span>&nbsp;&nbsp;&nbsp;</span><span style="color: #c8c9cc;font-size: 11px">{{item.createTime}}</span></div>
          <div class="comments">{{item.commentContent}}</div>
        </van-col>

        <!--  分割线-->
        <van-divider
          :style="{ color: '#D4D4D4', borderColor: '#D4D4D4', padding: '0 16px' }"
        >
        </van-divider>
      </van-row>

  <!--  分页-->
      <van-pagination v-model="currentPage" :page-count="pageCount" mode="simple" @change="queryAllByCarId()" />
    </div>
    <div v-else>
      <van-empty description="暂时还没有评论" />
    </div>

<!--    <van-skeleton title avatar :row="3" />-->

<!-- 弹出层 选择购买日期-->
    <van-popup
      v-model="show"
      closeable
      position="bottom"
      :style="{ height: '30%' }"
    >
      <van-form @submit="onSubmit">
<!--        日期弹出层-->
        <van-popup v-model="showPicker" position="bottom">
          <van-datetime-picker
            type="date"
            :min-date="minDate"
            @confirm="onConfirm"
            @cancel="showPicker = false"
          />
        </van-popup>
        <van-field
          readonly
          clickable
          name="startDate"
          :value="startTime"
          label="选择开始时间"
          placeholder="开始时间"
          @click="function() {
            showPicker = true;
            value = 'start'
          }"
          :rules="[{ validator,trigger : 'onChange', message: '请输入正确内容' }]"
        />
        <van-field
          readonly
          clickable
          name="endDate"
          :value="endTime"
          label="还车日期"
          placeholder="点击选择归还时间"
          @click="function() {
            showPicker = true;
            value = 'end';
          }"
          :rules="[{ validator,trigger : 'onChange', message: '请输入正确内容' }]"
        />

        <div style="margin: 16px;">
<!--          <van-button round block type="info" native-type="submit">提交订单</van-button>-->
          <van-submit-bar :price="totalPrice * 100"  button-text="提交订单"/>
        </div>
      </van-form>
    </van-popup>
<!--    商品购买 点击显示弹出层-->
    <div style="height: 50px;"></div>
    <div>
      <van-goods-action :safe-area-inset-bottom="true">
        <!--      <van-goods-action-icon icon="chat-o" text="客服" @click="onClickIcon" />-->
        <!--      <van-goods-action-icon icon="cart-o" text="购物车" @click="onClickIcon" />-->
        <!--      <van-goods-action-icon icon="shop-o" text="店铺" @click="onClickIcon" />-->
        <van-goods-action-icon :icon="isCollect" @click="changeCollect" :text="isCollect === 'star' ? '已收藏' : '收藏'" color="#ff5000" />
        <!--   点击将会显示商品规格页面   -->
        <van-goods-action-button
          type="danger"
          text="立即购买"
          @click="show = true"
        />
      </van-goods-action>
    </div>


  </div>


</template>

<script>
  import Vue from 'vue';

  import { Skeleton } from 'vant';
  import { Field } from 'vant';
  import { Button } from 'vant';
  import { Col, Row } from 'vant';
  import { Divider } from 'vant';
  import { Image as VanImage } from 'vant';
  import axios from "axios";
  import Global from "./Global";
  import { Pagination } from 'vant';
  import { Toast } from 'vant';
  import skuData from '../utils/data.js';
  import request from '@/utils/request'
  import { GoodsAction, GoodsActionIcon, GoodsActionButton } from 'vant';
  import { Popup } from 'vant';
  import { Form } from 'vant';
  import { DatetimePicker } from 'vant';
  import { Empty } from 'vant';
  import { SubmitBar } from 'vant';
  import { Swipe, SwipeItem } from 'vant';

  Vue.use(Swipe);
  Vue.use(SwipeItem);
  Vue.use(SubmitBar);
  Vue.use(Empty);
  Vue.use(DatetimePicker);
  Vue.use(Form);
  Vue.use(Popup);
  Vue.use(GoodsAction);
  Vue.use(GoodsActionButton);
  Vue.use(GoodsActionIcon);
  Vue.use(Toast);
  Vue.use(Pagination);
  Vue.prototype.$ajax = axios;
  Vue.use(VanImage);
  Vue.use(Divider);
  Vue.use(Col);
  Vue.use(Row);
  Vue.use(Button);
  Vue.use(Field);
  import { Cell, CellGroup } from 'vant';

  Vue.use(Cell);
  Vue.use(CellGroup);
  Vue.use(Skeleton);
    export default {
      name: "CarDetailPage",
      data(){
        return {
          images: [],
          message:"",
          carId: this.$route.query.carId,
          carList:[],
          totalPrice:0,
          records:{}, //所有评论
          currentPage: 1,  //当前页数
          pageCount: 1,  //总共的页数
          show: false,  //弹出层是否展示
          // 汽车购买弹出层
          showPicker: false, //是否显示时间选择
          value: "", //时间
          startTime: '', //表单
          endTime: '',  // 表单
          // 日期选择组件
          minDate: new Date(),
          isCollect: 'start-o', //是否收藏
          collect: {}, //查询的收藏记录
        }
      },
      created() {
        //查询车辆对应的评论
        this.queryAllByCarId();
        // 查询车辆的基本信息
        this.queryCarByid();
        // 查询是否被收藏
        this.getIsCollect();
      },
      methods:{
        queryAllByCarId(){
          console.log(this.currentPage);
          axios.get(Global.serverSrc + "/comment/queryByCarId",{
            params:{
              carId:this.$route.query.carId,
              page: this.currentPage,
              limit:20
            }
          })
            .then(res => {
              console.log(res.data);
              this.records = res.data.records;
              this.currentPage = res.data.current;
              this.pageCount = res.data.pages;
              return res.data;

            })
        },
        queryCarByid(){
          request({
            url: '/car/queryAllCar?carId='+ this.$route.query.carId ,
            method: 'get'
          }).then(res => {
            this.carList = res;
            this.images[0] = res[0].carimg;
            console.log(res)
          });
        },
        onChange(index) {
          Notify({ type: 'primary', message: index });
        },
        commitComment(){
          if (this.message.trim() == ""){
            Toast.fail("评论不能为空");
            return;
          }
          request({
            url: '/comment/customer/save',
            method: 'post',
            data:{commentContent:this.message,carId:this.$route.query.carId}
          }).then(res => {
            if(res.code != 200){
              Toast.fail(res.message);
              return;
            }
            Toast.success('评论成功');
            this.message = '';
            this.queryAllByCarId();
          });
        },
        getIsCollect(){  //查询是否被收藏
          request({
            url: '/collect/customer/isCollect?carId='+ this.$route.query.carId,
            method: 'get',
            data: {'carId': this.$route.query.carId}
          }).then(res => {
              this.isCollect = res.message == 1 ? 'star':'star-o';
              this.collect = res.data;
          });
        },
        changeCollect(){   // 更改收藏状态
          if (this.isCollect === 'star'){
            request({
              url: '/collect/customer/collect',       method: 'delete',
              data: {collectId: this.collect.collectId}
            }).then(res => {
              this.getIsCollect()
            });
          }else {
            request({
              url: '/collect/customer/collect',
              method: 'post',
              data: {carId: this.carId}
            }).then(res => {
              this.getIsCollect()
            });
          }
        },
        countPrice(){
          console.log("changeshijianchufa");
          var startdate = Date.parse(this.startTime);
          var enddate = Date.parse(this.endTime);
          console.log(isNaN(enddate));
          if (!isNaN(enddate) && enddate != ''){
            let totalDay = (enddate - startdate) / (1000*3600*24);
            console.log("总天数：", totalDay);
            this.totalPrice = this.carList[0].rentprice * totalDay;
          }
        },
        onSubmit(values) {    // 选择商品够购买 values是json可以直接操作
          if (!this.CompareDate(values['startDate'],values['endDate'])){
            Toast.fail("结束日期需要大于起止日期");
            return;
          }
          values['carId'] = this.carId;
          console.log('submit', values);
          this.addOrder(values);
        },
        addOrder(val){
          request({
            url: '/order/customer/save',
            method: 'post',
            data: val
          }).then(res => {
            if(res.code != 200){
              if (res.message == ""){
                Toast.fail("订单创建失败");
              }else{
                Toast.fail(res.message);
              }
              return;
            }
            Toast.success('订单创建成功！');
            this.$router.push({path:'/orderDetailPage',query:{order:res.data}});
          });
        },
        onConfirm(time) {   // 显示时间选择器
          if (this.value === "start"){
            this.startTime = this.dateFormat("YYYY-mm-dd",time);
          }
          if (this.value === "end"){
            this.endTime = this.dateFormat("YYYY-mm-dd",time);
          }
          // this.value = time;
          this.showPicker = false;
        },
        dateFormat(fmt, date) {  //格式化日期
          let ret;
          const opt = {
            "Y+": date.getFullYear().toString(),        // 年
            "m+": (date.getMonth() + 1).toString(),     // 月
            "d+": date.getDate().toString(),            // 日
            "H+": date.getHours().toString(),           // 时
            "M+": date.getMinutes().toString(),         // 分
            "S+": date.getSeconds().toString()          // 秒
            // 有其他格式化字符需求可以继续添加，必须转化成字符串
          };
          for (let k in opt) {
            ret = new RegExp("(" + k + ")").exec(fmt);
            if (ret) {
              fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
            };
          };
          return fmt;
        },
        CompareDate(start,end) {  //比较时间
          var startdate = Date.parse(start);
          var enddate = Date.parse(end);
          return enddate > startdate;
        },
        validator(val) {
          this.countPrice();
          return true;
        },
      }
    }
</script>

<style scoped>
  .header{
    width: 100%;
    height: 200px;
    background-color: #969799;
  }
  .commitbutton{
    margin-top: 99%;
  }
  .headPortrait{
    height: 70px;
    text-align:center;
  }
  .nickname{
    height: 25px;
    font-weight:bold;
    font-size: 14px;
    color: #ee0a24;
  }
  .comments{
    height: 45px;
    font-size: 14px;
  }
</style>
